package com.junlong0716.enjoylearning.service

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import com.junlong0716.enjoylearning.entity.rxevent.MusicPlayStateEvent
import com.junlong0716.enjoylearning.entity.rxevent.TimeCountDownLeftEvent
import com.junlong0716.module.common.rxbus.RxBus
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit


/**
 *@author: 巴黎没有摩天轮Li
 *@description:
 *@date: Created in 下午10:36 2018/6/6
 *@modified by:
 */
class TimerService : Service() {
    private var myBinder: MyBinder = MyBinder()
    private var timerDisposable: Disposable? = null

    inner class MyBinder : Binder() {
        fun getService(): TimerService {
            return this@TimerService
        }
    }

    override fun onBind(intent: Intent?): IBinder {
        return myBinder
    }

    override fun onCreate() {
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val timerClose = intent!!.getLongExtra("TIMER_CLOSE", 0)

        if (timerClose.toInt() == 0) {
            stopSelf()
        }

        if (timerDisposable != null && !timerDisposable!!.isDisposed) {
            timerDisposable!!.dispose()
        }

        Observable.interval(0, 1, TimeUnit.SECONDS) //0延迟  每隔1秒触发
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                .take(timerClose + 1) //设置循环次数
                .map { aLong -> timerClose - aLong }
                .doOnSubscribe {} //执行过程中按键为不可点击状态
                .subscribe(object : Observer<Long> {
                    override fun onComplete() {
                        RxBus.getDefault().post(MusicPlayStateEvent(0x9898, true))
                        stopSelf()
                        timerDisposable!!.dispose()
                    }

                    override fun onSubscribe(d: Disposable) {
                        timerDisposable = d
                    }

                    override fun onNext(t: Long) {
                        RxBus.getDefault().post(TimeCountDownLeftEvent(0x8989, t))
                    }

                    override fun onError(e: Throwable) {

                    }

                })
        return START_NOT_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        if (!timerDisposable!!.isDisposed) {
            timerDisposable!!.dispose()
        }
    }


}